#ifndef _MyRedisC_H_
#define _MyRedisC_H_

#include "TcpClient.h"
#include <iostream>
#include <string>
using namespace std;

// 继承 TcpClient
class MyRedisC: public TcpClient
{
private:
    int id;
    static const int BUF_SIZE = 1450;
    char sendbuf[BUF_SIZE];
    char recvbuf[BUF_SIZE];

public:
    MyRedisC(const char *_host, int port): TcpClient(_host, port)
    {
        start();
    }
    string set(string key, string val)
    {
        sprintf(sendbuf, "set %s %s", key.c_str(), val.c_str());
        io();
        string res(recvbuf);
        return res;
    }
    string get(string key, string defaultVal)
    {
        sprintf(sendbuf, "get %s ?", key.c_str());
        io();
        string res(recvbuf);
        if (res == "NULL")
            res = defaultVal;
        return res;
    }
    string remove(string key)
    {
        sprintf(sendbuf, "remove %s ?", key.c_str());
        io();
        string res(recvbuf);
        return res;
    }
    int worker() override
    {
        return 1;
    }
    void io()
    {
        /*每次读取一行，读取的数据保存在buf指向的字符数组中，成功，则返回第一个参数buf；*/
        /// 发送
        send(cli_fd, sendbuf, strlen(sendbuf), 0);
        /// 接收
        memset(recvbuf, 0, sizeof(recvbuf));
        recv(cli_fd, recvbuf, sizeof(recvbuf), 0);
    }
};

void testMyRedisC()
{
    MyRedisC *cli = new MyRedisC("127.0.0.1", 6378);
    cout << cli->set("name", "hhq") << endl;
    cout << cli->get("name", "yyq") << endl;
    cout << cli->remove("name") << endl;
    cout << cli->remove("name") << endl;
    cout << cli->get("name", "yyq") << endl;
    /**
        succ
        hhq
        succ
        notfound
        yyq
     */
}

#endif // _MyRedisC_H_
